package com.xbongbong.saas.model.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.DeleteDTO;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.DataUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.paas.field.SaasParticularAttributePoJo;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.ReturnedPurchaseDao;
import com.xbongbong.saas.domain.entity.ProductSerialFlowEntity;
import com.xbongbong.saas.domain.entity.ReturnedPurchaseProductEntity;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.ReturnedPurchaseEntityExt;
import com.xbongbong.saas.enums.RelativeProductEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.UpdateDataTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SerialEnum;
import com.xbongbong.saas.enums.product.RefundProductEnum;
import com.xbongbong.saas.enums.product.ReturnPurchaseProductEnum;
import com.xbongbong.saas.help.DefaultAttrHelp;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.ShowFormatHelp;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductSerialFlowModel;
import com.xbongbong.saas.model.ReturnedPurchaseModel;
import com.xbongbong.saas.model.ReturnedPurchaseProductModel;
import com.xbongbong.saas.model.ReturnedPurchaseSubDataModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.saas.util.StandardizeDataUtil;
import org.elasticsearch.action.support.WriteRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;

/**
 * @author Jian.Wang
 * @date  2019-01-25 14:08
 **/
@Service("ReturnedPurchaseModel")
public class ReturnedPurchaseModelImpl implements ReturnedPurchaseModel{

    private static final Logger LOG = LoggerFactory.getLogger(ReturnedPurchaseModelImpl.class);

    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private ReturnedPurchaseDao returnedPurchaseDao;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private ReturnedPurchaseSubDataModel returnedPurchaseSubDataModel;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private DefaultAttrHelp defaultAttrHelp;
    @Resource
    private ShowFormatHelp showFormatHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private ReturnedPurchaseProductModel returnedPurchaseProductModel;
    @Resource
    private ProductSerialFlowModel productSerialFlowModel;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private CommonHelp commonHelp;

    /**
     * 插入数据
     * @param entity 供应商实体
     * @return Integer
     * @throws XbbException 异常
     */
    @Override
    public Integer insert(ReturnedPurchaseEntityExt entity) throws XbbException {
        entity.setAddTime(DateTimeUtil.getInt());
        entity.setUpdateTime(DateTimeUtil.getInt());
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer insert = returnedPurchaseDao.insert(entity);

        PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
        BeanUtil.copyProperties(entity, paasFormDataEntity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE);
        paasEsModel.insert(insertDTO);
        paasFormSubDataModel.insertSubFormData(entity, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE_SUB);
        return insert;
    }

    /**
     * 更新数据
     * @param entity 采购退货单实体
     * @return Integer
     * @throws XbbException 异常
     */
    @Override
    public Integer update(ReturnedPurchaseEntityExt entity) throws XbbException {
        long now = DateTimeUtil.getInt();
        entity.setUpdateTime(now);
        paasFormSubDataModel.transferSubForm(entity, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE_SUB);
        StandardizeDataUtil.standardizeNotString(entity);
        Integer success = returnedPurchaseDao.update(entity);

        Integer updateSub = paasFormSubDataModel.updateSubFormData(entity, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE_SUB);
        if (Objects.equals(1, success) || Objects.equals(1, updateSub)) {
            // 更新时间
            success = returnedPurchaseDao.updateTime(now + 1, entity.getId(), entity.getCorpid());
            // 更新es
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(entity, paasFormDataEntity, false);
            InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE);
            insertDTO.getSource().remove("creatorId");
            paasEsModel.update(insertDTO);

        }
        if (Objects.nonNull(entity.getSubFormData()) && !entity.getSubFormData().isEmpty()) {
            entity.getData().putAll(entity.getSubFormData());
        }
        return success;
    }

    /**
     * 根据供应商ID查询采购退货单集合
     * @param param 参数
     * @return
     */
    @Override
    public List<ReturnedPurchaseEntityExt> getBySupplierId(Map<String, Object> param) {
        return returnedPurchaseDao.getBySupplierId(param);
    }

    /**
     * 根据条件查询数据
     * @param param 参数
     * @return List<ReturnedPurchaseEntityExt>
     */
    @Override
    public List<ReturnedPurchaseEntityExt> findEntitys(Map<String, Object> param) {
        List<ReturnedPurchaseEntityExt> entitys = returnedPurchaseDao.findEntitys(param);
        Object corpid = param.get(ParameterConstant.CORPID);
        if (Objects.nonNull(corpid)) {
            paasFormSubDataModel.findSubEntity(corpid.toString(), entitys, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE_SUB);
        }
        return entitys;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        return returnedPurchaseDao.getEntitysCount(param);
    }

    /**
     * 查询单个实体
     *
     */
    @Override
    public ReturnedPurchaseEntityExt getByKey(Long key, String corpid) {
        ReturnedPurchaseEntityExt entityExt = returnedPurchaseDao.getByKey(key, corpid);
        paasFormSubDataModel.findSubEntity(corpid, Collections.singletonList(entityExt), IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE_SUB);
        return entityExt;
    }

    @Override
    public Integer deleteBatch(List<Long> idIn, String corpid) throws XbbException {
        Integer integer = returnedPurchaseDao.deleteBatch(idIn, corpid);
        paasEsModel.deleteBatch(idIn, corpid, DelEnum.DELETE.getDel(), IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE);

        paasFormSubDataModel.deleteBatchByDataId(idIn, corpid, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE_SUB, DelEnum.DELETE_SUBFORM);
        return integer;
    }

    @Override
    public Integer deleteByKey(Long key,String corpid) throws XbbException{
        DeleteDTO deleteDTO = new DeleteDTO();
        deleteDTO.setEsId(corpid+"_"+key);
        deleteDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE);
        paasEsModel.delete(deleteDTO);

        paasFormSubDataModel.deleteByDataId(key, corpid, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE_SUB);
        return returnedPurchaseDao.deleteByKey(key,corpid);
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = returnedPurchaseDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE);
        }
        if (!subList.isEmpty()) {
            returnedPurchaseSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = returnedPurchaseDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE, refreshPolicy);
        }
        if (!subList.isEmpty()) {
            returnedPurchaseSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public Integer updateBatch(List<UpdateDataEntity> updateList, String corpid, boolean needThrow) throws XbbException {
        StandardizeDataUtil.standardizeList(updateList);
        Integer integer = returnedPurchaseDao.updateBatch(updateList, corpid);
        paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE, needThrow);
        return integer;
    }

    @Override
    public Integer update(List<UpdateDataEntity> updateList,String corpid) throws XbbException{
        //1. 先拿到子表单数据
        List<UpdateDataEntity> subList = DataUtil.getUpdateSubDataList(updateList);
        // 2. 主表删掉子表单数据
        DataUtil.removeSubDataInData(updateList);
        Integer integer = 0;
        if (CollectionsUtil.isNotEmpty(updateList)) {
            StandardizeDataUtil.standardizeList(updateList);
            integer = returnedPurchaseDao.updateBatch(updateList, corpid);
            paasEsModel.updateBatchMuchField(updateList, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE, WriteRequest.RefreshPolicy.NONE);
        }
        if (!subList.isEmpty()) {
            returnedPurchaseSubDataModel.updateBatch(subList, corpid);
        }
        return integer;
    }

    @Override
    public List<String> getCorpids() {
        return returnedPurchaseDao.getCorpids();
    }

    @Override
    public Integer batchUpdateOwner(List<Long> dataIdList, String corpid, String userId, WriteRequest.RefreshPolicy refreshPolicy) throws XbbException {
        Integer integer = returnedPurchaseDao.batchUpdateOwner(dataIdList, corpid, userId);
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (Long id : dataIdList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(corpid+"_"+id);
            Map<String, Object> map = new HashMap<>();
            map.put(FieldTypeEnum.OWNERID.getAlias(), userId);
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE);
            insertDTOList.add(insertDTO);
        }
        paasEsModel.updateBatch(insertDTOList, refreshPolicy);
        return integer;
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return returnedPurchaseDao.findEntitys(param);
    }

    /**
     * 编辑时格式化解释
     *
     * @param formatExplainDTO 入参
     * @throws XbbException 异常
     */
    @Override
    public void formatUpdateExplain(FormatExplainDTO formatExplainDTO) throws XbbException {
        List<FieldAttrEntity> explainList = formatExplainDTO.getExplainList();
        String corpid = formatExplainDTO.getCorpid();
        String platForm = formatExplainDTO.getPlatform();
        PaasFormDataEntityExt dataEntity = formatExplainDTO.getDataEntity();
        boolean unitNoEdit = false;
        boolean formCopy = Objects.nonNull(formatExplainDTO.getSaasSpecialParamPojo()) && Objects.equals(formatExplainDTO.getSaasSpecialParamPojo().getFromCopy(), BasicConstant.ONE);
        if (Objects.nonNull(dataEntity) && !formCopy) {
            if (!Objects.equals(dataEntity.getData().getInteger(ReturnedPurchaseEnum.RETURNED_STATUS.getAttr()), BasicConstant.ONE)) {
                unitNoEdit = true;
            }
        }
        for (FieldAttrEntity fieldAttrEntity : explainList) {
            Integer fieldType = fieldAttrEntity.getFieldType();
            if (Objects.equals(fieldType, FieldTypeEnum.SELECT_PRODUCT.getType())) {
                explainHelp.formatSelectProductExplains(fieldAttrEntity, XbbRefTypeEnum.RETURNED_PURCHASE, corpid, BasicConstant.ONE, unitNoEdit);
                if (Objects.equals(platForm, PlatFormEnum.DINGTALK.getValue())) {
                    SaasParticularAttributePoJo saasParticularAttributePoJo = fieldAttrEntity.getSaasParticularAttributePoJo();
                    saasParticularAttributePoJo.setProductRelyAttr(ReturnedPurchaseEnum.PURCHASE_SHEET_ID.getAttr());
                }
                try {
                    String outstockId = formatExplainDTO.getResult().getString(ReturnedPurchaseEnum.OUTSTOCK_ID.getAttr());
                    if (StringUtil.isNotEmpty(outstockId) && !Objects.equals(outstockId, "0")) {
                        fieldAttrEntity.setEditable(0);
                        List<? extends FieldAttrEntity> subExplainList = fieldAttrEntity.getSubForm().getItems();
                        subExplainList.forEach(item -> item.setEditable(0));
                        fieldAttrEntity.getSubForm().setItems(subExplainList);
                    }
                } catch (Exception e) {
                    LOG.error("编辑采购退货单格式化产品解释出错");
                }
            }
            if (Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseEnum.LINK_SUPPLIER.getAttr())||Objects.equals(fieldAttrEntity.getAttr(),ReturnedPurchaseEnum.PURCHASE_SHEET_ID.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }
            if (Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseEnum.MANAGER_ID.getAttr())) {
                if(fieldAttrEntity.getDefaultAttr() == null || (fieldAttrEntity.getDefaultAttr() != null && fieldAttrEntity.getDefaultAttr().getDefaultList() == null)) {
                    fieldAttrEntity.setDefaultAttr(defaultAttrHelp.setUserDefaultAttrPoJo(formatExplainDTO.getUserId(), formatExplainDTO.getLoginUser().getName(),formatExplainDTO.getLoginUser().getAvatar()));
                }
            } else if (Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseEnum.INVOICES.getAttr())) {
                fieldAttrEntity.setEditable(0);
            } else if (Objects.equals(fieldAttrEntity.getAttr(), ReturnedPurchaseEnum.PAY_SHEETS.getAttr())) {
                fieldAttrEntity.setEditable(0);
            }
        }
    }

    /**
     * 采购退货单编辑格式化数据格式
     *
     * @param saasAnalysisDataDTO saas编辑数据
     * @param result               要返回的jsonobject
     * @throws XbbException 参数格式错误异常
     * @author Jian.Wang
     * @date 2019/1/23 20:00
     * @since v1.0
     **/
    @Override
    public void formatData(SaasAnalysisDataDTO saasAnalysisDataDTO, JSONObject result) throws XbbException {
//        formatProduct4Show(result,saasAnalysisDataDTO);
        showFormatHelp.formatLinkBusiness4Show(result,ReturnedPurchaseEnum.PURCHASE_SHEET_ID.getAttr(),ReturnedPurchaseEnum.PURCHASE_SHEET_ID_LINKED_TEXT.getAttr(),ReturnedPurchaseEnum.PURCHASE_SHEET_ID.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result,ReturnedPurchaseEnum.LINK_SUPPLIER.getAttr(),ReturnedPurchaseEnum.LINK_SUPPLIER_HIDE.getAttr(),ReturnedPurchaseEnum.LINK_SUPPLIER.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, ReturnedPurchaseEnum.PAY_SHEETS.getAttr(), ReturnedPurchaseEnum.PAY_SHEETS_LINKED_TEXT.getAttr(), ReturnedPurchaseEnum.PAY_SHEETS.getFieldType());
        showFormatHelp.formatLinkBusiness4Show(result, ReturnedPurchaseEnum.INVOICES.getAttr(), ReturnedPurchaseEnum.INVOICES_LINKED_TEXT.getAttr(), ReturnedPurchaseEnum.INVOICES.getFieldType());
    }

    @Override
    public JSONObject formatSingleProduct(ReturnedPurchaseProductEntity returnedPurchaseProductEntity, Boolean isEdit) {
        JSONObject json = returnedPurchaseProductEntity.getData();
        double rate = showFormatHelp.approvalSetBusinessUnit(json, returnedPurchaseProductEntity);
        if (Objects.isNull(json) || json.isEmpty()) {
            json = new JSONObject();
            for (ReturnPurchaseProductEnum returnPurchaseProductEnum : ReturnPurchaseProductEnum.values()){
                String attr = returnPurchaseProductEnum.getAttr();
                switch (returnPurchaseProductEnum){
                    case PRODUCT:
                        json.put(attr,returnedPurchaseProductEntity.getProductId());
                        break;
                    case NUM:
                        json.put(attr,returnedPurchaseProductEntity.getProductNum());
                        break;
                    case PURCHASE_PRICE:
                        json.put(attr,returnedPurchaseProductEntity.getProductPrice());
                        break;
                    case SUBTOTAL:
                        json.put(attr,returnedPurchaseProductEntity.getProductPrice() * returnedPurchaseProductEntity.getProductNum());
                        break;
                    case UNIT:
                        json.put(attr,returnedPurchaseProductEntity.getProductUnit());
                        break;
                    default:
                        break;
                }
            }
        }else if (isEdit){
            //列表和编辑页格式不一致
            if (Objects.nonNull(json.getString(SelectProductEnum.BATCH.getAttr()))) {
                JSONObject refundBatch = new JSONObject();
                refundBatch.put("text", json.getString(SelectProductEnum.BATCH.getAttr()));
                refundBatch.put("value", json.getString(SelectProductEnum.BATCH.getAttr()));
                json.put(RefundProductEnum.BATCH.getAttr(), refundBatch);
            }
            if (Objects.nonNull(json.getString(SelectProductEnum.WAREHOUSE.getAttr())) && !(json.get(SelectProductEnum.WAREHOUSE.getAttr()) instanceof JSONArray)) {
                JSONObject wareHouseObj = new JSONObject();
                wareHouseObj.put("id", json.getString(SelectProductEnum.WAREHOUSE.getAttr()));
                wareHouseObj.put("name", json.getString("warehouseName"));
                JSONArray jsonArray = new JSONArray();
                jsonArray.add(wareHouseObj);
                json.put(SelectProductEnum.WAREHOUSE.getAttr(), jsonArray);
            }
        }
        json.put(ReturnPurchaseProductEnum.OUTSTOCK_NUM.getAttr(), Arith.div(returnedPurchaseProductEntity.getOutstockNum(), rate));
        json.put(ReturnPurchaseProductEnum.WAIT_OUTSTOCK_NUM.getAttr(),Arith.div(Arith.sub(returnedPurchaseProductEntity.getProductNum(),returnedPurchaseProductEntity.getOutstockNum()), rate));
        return json;
    }

    @Override
    public void formatProduct4Show2(Long dataId, String corpid, JSONObject data,  Boolean forProcess, Integer operate, UpdateDataTypeEnum updateDataTypeEnum) throws XbbException {
        // 获取关联产品
        List<ReturnedPurchaseProductEntity> returnedPurchaseProductEntityList = new ArrayList<>();
        Map<Long, JSONArray> refProductSeqMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.isNull(dataId) || Objects.equals(dataId, 0L)) {
            if (data.get(ReturnedPurchaseEnum.PRODUCTS.getAttr()) instanceof JSONObject) {
                JSONArray productArr = FastJsonHelper.getJsonArrOrDefaultFromFormData(FastJsonHelper.getJsonObjectOrDefaultFromFormData(data, ReturnedPurchaseEnum.PRODUCTS.getAttr(), new JSONObject()), StringConstant.PRODUCT_LIST, new JSONArray());
                Map<Long, ProductEntityExt> productMap = productModel.getProductMap(corpid, productArr);
                getProductList(corpid, returnedPurchaseProductEntityList, productArr, productMap);
            } else {
                JSONArray jsonArray = data.getJSONArray(ReturnedPurchaseEnum.PRODUCTS.getAttr());
                if (Objects.nonNull(jsonArray)) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        ReturnedPurchaseProductEntity returnedPurchaseProductEntity = new ReturnedPurchaseProductEntity();
                        Long subProductId = FastJsonHelper.getLongFromFormData(jsonObject, BusinessConstant.PRODUCT_SUB_ID);
                        if (Objects.nonNull(subProductId)) {
                            returnedPurchaseProductEntity.setId(subProductId);
                        }
                        returnedPurchaseProductEntity.setData(jsonObject);
                        returnedPurchaseProductEntityList.add(returnedPurchaseProductEntity);
                    }
                }
            }
        } else {
            // 检索del=0和del=6的数据，del=6是工作流中审批节点拒绝和撤回产生的数据，不是通过审批拒绝、撤回的数据不会产生del=6的数据，如果拒绝和撤回重新提交后，del=6将会被置回del=0
            returnedPurchaseProductEntityList = returnedPurchaseProductModel.getProductsByRetPurchaseId(corpid, dataId, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.APPROVE_FAILED.getDel()));
            if (commonHelp.isOpenWorkFlow(corpid) && Objects.nonNull(forProcess) && forProcess && Objects.equals(WorkflowOperateEnum.ADD.getType(), operate)) {
                // 工作流的详情，需要从上下文中拼接序列号数据
                JSONArray productArray = data.getJSONArray(ReturnedPurchaseEnum.PRODUCTS.getAttr());
                for (int i = 0; i < productArray.size(); i++) {
                    JSONObject jsonObject = productArray.getJSONObject(i);
                    refProductSeqMap.put(jsonObject.getLong(BusinessConstant.PRODUCT_SUB_ID), jsonObject.getJSONArray(ProductConstant.SEQ));
                }
            } else {
                // 表单序列号流水
                List<ProductSerialFlowEntity> productSerialFlowList = productSerialFlowModel.getFlowByRefIdAndBusiness(Collections.singletonList(dataId), XbbRefTypeEnum.RETURNED_PURCHASE.getCode(), corpid);
                for (ProductSerialFlowEntity entity : productSerialFlowList) {
                    JSONArray serialArray = refProductSeqMap.getOrDefault(entity.getRefProductId(), new JSONArray());
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(SerialEnum.SERIAL.getAttr(), entity.getSeq());
                    jsonObject.put(SerialEnum.MEMO.getAttr(), entity.getMemo());
                    serialArray.add(jsonObject);

                    refProductSeqMap.put(entity.getRefProductId(), serialArray);
                }
            }

            returnedPurchaseProductEntityList.forEach(item -> {
                JSONArray seqArray = refProductSeqMap.getOrDefault(item.getId(), null);
                if (Objects.nonNull(seqArray)) {
                    item.getData().put(ProductConstant.SEQ, seqArray);
                }
            });
        }
        JSONArray productArray = new JSONArray();
        for (ReturnedPurchaseProductEntity returnedPurchaseProductEntity : returnedPurchaseProductEntityList){
            JSONObject json = formatSingleProduct(returnedPurchaseProductEntity, true);
            if (updateDataTypeEnum.isUpdate()){
                json.put(BusinessConstant.PRODUCT_SUB_ID,returnedPurchaseProductEntity.getId());
                if (Objects.isNull(returnedPurchaseProductEntity.getId())) {
                    json.put(BusinessConstant.PRODUCT_SUB_ID,0);
                }
            }else {
                json.put(BusinessConstant.PRODUCT_SUB_ID,0);
            }
            if (updateDataTypeEnum.isLinkAdd()){
                json.put(SelectProductEnum.UNIT.getAttr(), saasFormHelp.formatUnit(returnedPurchaseProductEntity.getCorpid(),returnedPurchaseProductEntity.getProductUnit()));
            }
            // 源单编号字段，移动端顶部渲染需要
            if (json.containsKey(SelectProductEnum.SOURCE_DOC.getAttr())) {
                json.put(SelectProductEnum.SOURCE_SOURCE_DOC.getAttr(), json.get(SelectProductEnum.SOURCE_DOC.getAttr()));
            }
            json.put(SelectProductEnum.SOURCE_PRICE.getAttr(),json.get(SelectProductEnum.PRICE.getAttr()));
            json.put("refId",returnedPurchaseProductEntity.getId());
            json.put("editableSerial", 1);
            productArray.add(json);
        }
        data.put(ReturnedPurchaseEnum.PRODUCTS.getAttr(),productArray);
    }

    @Override
    public void getProductList(String corpid, List<ReturnedPurchaseProductEntity> retPurchaseProductEntityList, JSONArray productArray, Map<Long, ProductEntityExt> productMap) throws XbbException {
        Integer sort = 0;
        for (int i = 0; i < productArray.size(); i++) {
            JSONObject productArrayJSONObject = productArray.getJSONObject(i);
            sort++;
            // 页面传入的产品id
            Long pageProductId = FastJsonHelper.getLongOrDefaultFromFormData(productArrayJSONObject, StringConstant.SAAS_LINK_BUSINESS_ID, 0L);
            // 产品数量
            Double productNum = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.NUM.getSaasAttr(), 0D);
            // 产品备注
            String memo = FastJsonHelper.getStringOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.MEMO.getSaasAttr(), "");
            // 产品价格
            Double productPrice = getDoubleOrDefaultFromFormData(productArrayJSONObject, RelativeProductEnum.PRODUCT_PRICE.getSaasAttr(), 0D);
            if (productMap.containsKey(pageProductId)) {
                ProductEntityExt product = productMap.get(pageProductId);
                JSONObject productObject = product.getData();
                String specification = FastJsonHelper.getStringOrDefaultFromFormData(product.getData(), ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), "");
                String productName = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.NAME.getAttr(), "");
                String productNo = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.PRODUCT_NO.getAttr(), "");
                String barcode = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.BARCODE.getAttr(), "");
                String unit = FastJsonHelper.getStringOrDefaultFromFormData(productObject, ProductEnum.UNIT.getAttr(), "");
                Long parentId = FastJsonHelper.getLongOrDefaultFromFormData(productObject, ProductEnum.PARENT_ID.getAttr(), 0L);
                ReturnedPurchaseProductEntity productEntity = new ReturnedPurchaseProductEntity();
                productEntity.setCorpid(corpid);
                productEntity.setBarcode(barcode);
                productEntity.setProductUnit(unit);
                productEntity.setProductId(pageProductId);
                productEntity.setParentId(parentId);
                productEntity.setProductNum(productNum);
                productEntity.setProductName(productName);
                productEntity.setProductNo(productNo);
                productEntity.setProductSpecification(specification);
                productEntity.setProductPrice(productPrice);
                productEntity.setMoney(productPrice*productNum);
                productEntity.setMemo(memo);
                productEntity.setSort(sort);
                /*JSONObject jsonObject = new JSONObject();
                jsonObject.put(ReturnPurchaseProductEnum.PRODUCT.getAttr(), pageProductId);
                jsonObject.put(ReturnPurchaseProductEnum.UNIT.getAttr(), unit);
                jsonObject.put(ReturnPurchaseProductEnum.NUM.getAttr(), productNum);
                jsonObject.put(ReturnPurchaseProductEnum.SUBTOTAL.getAttr(), productPrice * productNum);
                jsonObject.put(ReturnPurchaseProductEnum.PURCHASE_PRICE.getAttr(), productPrice);
                jsonObject.put(ReturnPurchaseProductEnum.MEMO.getAttr(), memo);
                productEntity.setData(jsonObject);*/
                retPurchaseProductEntityList.add(productEntity);
            }
        }
    }

}
